import { createMemo, mergeProps, splitProps, type Component } from "solid-js";
import { type FcInputProps } from "./types";
import type { JSX } from "solid-js/jsx-runtime";
import { wrapClasses } from "@lib/types";
import { IsNotNullOrUndefined } from "@lib/helper";

const defaultProps: Partial<FcInputProps> = {
  type: "text",
};

const FcInput: Component<FcInputProps> = (props) => {
  const [local, elProps] = splitProps(mergeProps({ type: "text" }, props), [
    "value",
    "onValueChanged",
    "ref",
    "$ServerOnly",
    "classList",
    "controlSize",
    "readonlyPlainText",
  ]);

  const classList = createMemo(() => {
    return {
      ...wrapClasses(local.classList),
      [`form-control-${local.controlSize}`]: IsNotNullOrUndefined(
        local.controlSize
      ),
      ["form-control-plaintext"]: local.readonlyPlainText,
    };
  });

  const handleOnChange: JSX.InputHTMLAttributes<HTMLInputElement>["onChange"] =
    (el) => {
      local.onValueChanged?.(el.target.value);
    };

  return (
    <input
      ref={local.ref}
      class="form-control"
      value={local.value}
      onChange={handleOnChange}
      classList={classList()}
      {...elProps}
    ></input>
  );
};

export type * from "./types";
export default FcInput;
